package com.jeeplus.modules.common.excel.common.validator.impl.base;

import com.jeeplus.common.utils.StringUtil;
import com.jeeplus.modules.common.excel.common.anno.base.IsMobilePhone;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;
import com.jeeplus.modules.common.utils.CommonUtils;

import java.lang.reflect.Field;

/**
 * @author wang.yishu
 * @version 1.0
 * @className IsMobilePhoneValidator
 * @description TODO
 * @date 2022/7/11 17:38
 */
public class IsMobilePhoneValidator extends AbstractValidator {

    private IsMobilePhone isMobilePhone;

    @Override
    public boolean canValidate(Field field) {
        isMobilePhone =  field.getDeclaredAnnotation(IsMobilePhone.class);
        return isMobilePhone != null;
    }

    @Override
    public String toValidate(Object entity, Field field) {
        field.setAccessible(true);
        try {
            Object mobilePhoneValue = field.get(entity);
            if (mobilePhoneValue instanceof String) {
                String mobilePhoneStr = mobilePhoneValue.toString();
                if (StringUtil.isNotBlank(mobilePhoneStr)) {
                    if (!CommonUtils.isMobile(mobilePhoneStr)) {
                        return isMobilePhone.msg();
                    }
                }
            } else {
                return isMobilePhone.msg();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
